package com.keur.money.data.analyse.util

import android.app.Application
import android.os.Handler
import android.os.Looper
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.keur.money.base.utils.log.MullaLog
import com.keur.money.data.analyse.AnalyseBuilder
import com.keur.money.data.analyse.bean.GoogleBean

object GoogleUtil {

    /**
     * google play 返回的install referrer，
     * 建议每个接口都需要带上这个字段
     */
    private var _installReferrer: String = ""

    private var _installReferrerClient: InstallReferrerClient? = null

    /**
     * 初始化google install referrer 模块
     *
     * @param context Application
     */
    fun init(context: Application) {
        init(context) {
            saveS2sInfo()
        }
    }

    /**
     * 初始化google install referrer 模块
     *
     * @param context Application
     * @param success 成功回调
     */
    fun init(context: Application, success: (String) -> Unit) {
        try {
            if (_installReferrer.isBlank()) {
                Thread {
                    if (Looper.getMainLooper() != Looper.myLooper()) {
                        _installReferrerClient = InstallReferrerClient.newBuilder(context).build()
                        _installReferrerClient?.let {
                            it.startConnection(object : InstallReferrerStateListener {
                                override fun onInstallReferrerSetupFinished(responseCode: Int) {
                                    when (responseCode) {
                                        InstallReferrerClient.InstallReferrerResponse.OK -> {
                                            try {
                                                _installReferrer = it.installReferrer?.installReferrer ?: ""
                                                it.endConnection()
                                                Handler(Looper.getMainLooper()).post {
                                                    //回调通知
                                                    success.invoke(getInstallReferrer())
                                                }
                                            } catch (e: Exception) {
                                                MullaLog.e(e.message)
                                                it.endConnection()
                                            }
                                        }

                                        InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED -> {
                                            MullaLog.i("FEATURE_NOT_SUPPORTED")
                                            it.endConnection()
                                        }

                                        InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE -> {
                                            MullaLog.i("SERVICE_UNAVAILABLE")
                                            it.endConnection()
                                        }
                                    }
                                }
                                override fun onInstallReferrerServiceDisconnected() {
                                }
                            })
                        }

                    } else {
                        MullaLog.i("init google installReferrerClient ERROR!!! Cannot call in the main thread, You must call in the other thread")
                        Handler(Looper.getMainLooper()).post {
                            //回调通知
                            success.invoke(getInstallReferrer())
                        }
                    }
                }.start()
            } else {
                //回调通知
                success.invoke(getInstallReferrer())
            }
        } catch (e: Exception) {
            MullaLog.e(e.message)
            //回调通知
            success.invoke(getInstallReferrer())
        }
    }

    /**
     * 获取Install Referrer
     * gclid123
     */
    fun getInstallReferrer(): String {
        return _installReferrer
    }

    /**
     * 保存google s2s信息
     */
    fun saveS2sInfo() {
        val path = AnalyseBuilder.pathGoogleInstall
        val url = UrlHelper.combineUrl(path)
        val body = GoogleBean(
            channelCode = getInstallReferrer(),
            subChannelCode = getInstallReferrer()
        ).encrypt(path)
        AnalysisHttpHelper.doPostAction(url, body)
    }
}